﻿using System;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Core.Extensions;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extension;

namespace Web.Passport.Controllers
{
    public class PasswordController : BaseController
    {
        private const string PwdResetCaptchaKey = "pwd.reset";
        public PasswordController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }
        #region 通过注册邮箱/绑定邮箱重置密码
        /// <summary>
        /// 通过注册邮箱/绑定邮箱找回密码
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="email">注册邮箱/绑定邮箱</param>
        /// <param name="captcha">验证码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(string email, string captcha)
        {
            var result = new MagicKit<string>();
            if (!email.IsEmail())
            {
                result.Message = "请输入正确的电子邮箱地址！";
                return Json(result);
            }
            if (!CaptchaValidateInternal(PwdResetCaptchaKey, captcha))
            {
                result.Message = "请输入正确的验证码！";
                return Json(result);
            }
            var exist = Passport.Value.UserExist(email);
            //exist.Data 为用户Id
            //exist.Message 为用户Name
            if (exist.Status)
            {
                var auth = new AuthEmail();
                var id = Guid.NewGuid().ToString().ToUpper();
                auth.Id = id;
                auth.UserId = exist.Data;
                auth.Group = 2;
                auth.Email = email;
                auth.Status = false;
                auth.CreatedBy = exist.Message;
                auth.CreatedOn = DateTime.Now;
                var status = Extra.Value.AuthEmailCreate(auth);

                if (status)
                {
                    result.Status = true;
                    //todo 发送邮件
                }
                else
                {
                    result.Message = "发送邮件失败！";
                }
            }
            else
            {
                result.Message = "该电子邮箱不存在，请重新输入！";
            }
            return Json(result);
        }

        /// <summary>
        /// 通过邮箱重置密码
        /// </summary>
        /// <param name="param">邮件验证</param>
        /// <returns></returns>
        public ActionResult ResetByEmail(string param)
        {
            var model = new MagicKit<string>();

            var auth = Extra.Value.AuthEmailGet(param, 2);
            if (auth != null)
            {
                if (!auth.Status)
                {
                    model.Status = true;
                    model.Data = auth.Email;
                    model.Message = param;
                }
                else
                {
                    model.Message = "链接已失效，请重新获取有效链接！";
                }
            }
            else
            {
                model.Message = "参数不正确或该链接已失效！";
            }

            return View(model);
        }

        /// <summary>
        /// 通过邮箱重置密码
        /// </summary>
        /// <param name="param"></param>
        /// <param name="password"></param>
        /// <param name="rePassword"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetByEmail(string param, string password, string rePassword)
        {
            var result = new MagicKit<string>();
            if (password != rePassword)
            {
                result.Message = "两次输入的密码不一致!";
                return Json(result);
            }
            var auth = Extra.Value.AuthEmailGet(param, 2);
            if (auth != null && !auth.Status)
            {
                var user = Passport.Value.UserGet(auth.UserId);
                if (user != null)
                {
                    var newPassword = (password.HashPassword() + PasswordSalt).HashPassword();
                    var status = Passport.Value.UserPasswordUpdate(user.Id, newPassword);
                    if (status)
                    {
                        result.Status = true;
                        Extra.Value.AuthEmailStatusUpdate(param);
                    }
                    else
                    {
                        result.Message = "更新密码失败！";
                    }
                }
                else
                {
                    result.Message = "用户不存在！";
                }
            }
            else
            {
                result.Message = "链接无效或已过期，请重新获取有效链接！";
            }
            return Json(result);
        }
        #endregion

        /// <summary>
        /// 通过手机号重置密码
        /// </summary>
        /// <returns></returns>
        public ActionResult ResetByMobile()
        {
            return View();
        }

        /// <summary>
        /// 通过手机号重置密码
        /// </summary>
        /// <param name="mobile">注册/绑定手机号</param>
        /// <param name="password">新密码</param>
        /// <param name="rePassword">确认新密码</param>
        /// <param name="authId">短信验证Id</param>
        /// <param name="authCode">短信验证码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetByMobile(string mobile, string password, string rePassword, string authId, string authCode)
        {
            var result = new MagicKit<string>();

            if (!mobile.IsMobile())
            {
                result.Message = "请输入正确的手机号码！";
                return Json(result);
            }
            if (authCode.IsNullOrEmpty())
            {
                result.Message = "请输入短信验证码！";
                return Json(result);
            }
            if (!password.IsPassword() || !rePassword.IsPassword())
            {
                result.Message = "请输入新密码！";
                return Json(result);
            }
            if (password != rePassword)
            {
                result.Message = "两次输入的密码不一致！";
                return Json(result);
            }

            var auth = Extra.Value.AuthSmsGet(authId, mobile, 2, authCode);
            if (auth != null && !auth.Status && mobile == auth.Mobile)
            {
                var user = Passport.Value.UserGet(auth.UserId);
                var newPassword = (password.HashPassword() + PasswordSalt).HashPassword();
                var status = Passport.Value.UserPasswordUpdate(user.Id, newPassword);
                if (status)
                {
                    result.Status = true;
                    Extra.Value.AuthSmsStatusUpdate(authId);
                }
                else
                {
                    result.Message = "设置密码失败！";
                }
            }
            else
            {
                result.Message = "手机号码不正确或短信验证码已过期！";
            }
            return Json(result);
        }
    }
}
